package com.item.mofan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.item.mofan.common.BaseContext;
import com.item.mofan.common.Result;
import com.item.mofan.dto.OrdersDto;
import com.item.mofan.entity.*;
import com.item.mofan.exception.CustomException;
import com.item.mofan.mapper.OrdersMapper;
import com.item.mofan.mapper.UserMapper;
import com.item.mofan.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Override
    public void submit(Orders orders) {
        Long userId= BaseContext.getCurrentId();
        //获取购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        //判断购物车是否为空
        if (shoppingCarts==null&&shoppingCarts.size()==0){
            throw new CustomException("购物车为空,请添加菜品后再提交订单");
        }
        User user=userService.getById(userId);
        Long addressBookId=orders.getAddressBookId();
        AddressBook addressBook=addressBookService.getById(addressBookId);
        //判断地址是否为空
        if (addressBook==null){
            throw new CustomException("无填写送货地址");
        }
        Long orderId= IdWorker.getId();
        AtomicInteger amount=new AtomicInteger(0);
        //遍历购物车数据，
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(item.getName());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setImage(item.getImage());
            orderDetail.setSetmealId(item.getSetmealId());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //向订单插入一条数据
        orders.setNumber(String.valueOf(orderId));
        orders.setId(orderId);
        orders.setUserId(userId);
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(new BigDecimal(amount.get()));
        this.save(orders);
        //插入多条订单详情
        orderDetailService.saveBatch(orderDetails);
        //清空购物车
        shoppingCartService.remove(queryWrapper);
    }

    /**
     * 管理订单列表
     * @param page
     * @param pageSize
     * @param orders
     * @return
     */
    @Override
    public Page<Orders> getPage(int page, int pageSize, Orders orders,String endTime,String beginTime) {
        Page<Orders> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(orders.getNumber()!=null,Orders::getNumber,orders.getNumber());
        if (StringUtils.isNotBlank(beginTime)){
            queryWrapper.ge(Orders::getOrderTime,beginTime);
        }
        if (StringUtils.isNotBlank(endTime)){
            queryWrapper.le(Orders::getOrderTime,endTime);
        }
        Page<Orders> ordersPage = ordersService.page(pageInfo, queryWrapper);
        return ordersPage;
    }

    /**
     * 用户订单列表
     * @param page
     * @param pageSize
     * @return
     */
    public Page<OrdersDto> getUserPage(int page,int pageSize){
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);
        //获取用户信息
        Long userId = BaseContext.getCurrentId();
        User user=userService.getById(userId);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Orders::getUserId, userId);
            queryWrapper.orderByDesc(Orders::getOrderTime);

            ordersService.page(ordersPage, queryWrapper);

            BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        List<Orders> ordersList = ordersPage.getRecords();

        List<OrdersDto> ordersDtoList = ordersList.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);//把item数据拷贝给Dto对象
            Long ordersId=item.getId();
            //查询订单号下的订单项
            LambdaQueryWrapper<OrderDetail> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,ordersId);
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper1);
            //赋值给orderDto
            ordersDto.setOrderDetails(orderDetailList);
            Long addressId=item.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressId);
            ordersDto.setAddress(addressBook.getDetail());
            ordersDto.setConsignee(addressBook.getConsignee());
            ordersDto.setUserName(user.getName());
            ordersDto.setPhone(addressBook.getPhone());
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return ordersDtoPage;
    }
}
